package com.example.its2021606134chh.LifeIndexModule;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.example.its2021606134chh.HttpUtil;
import com.example.its2021606134chh.R;
import com.example.its2021606134chh.ThresholdModule.ThresholdActivity;
import com.example.its2021606134chh.ThresholdModule.ThresholdParams;
import com.google.gson.Gson;

import java.util.Timer;
import java.util.TimerTask;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link LifeIndexFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class LifeIndexFragment extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "title";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    IndexUI indUV, indClod, indDress, indMotion, indAir;

    public LifeIndexFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment LifeIndexFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static LifeIndexFragment newInstance(String param1, String param2) {
        LifeIndexFragment fragment = new LifeIndexFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_life_index, container, false);
        // Inflate the layout for this fragment
        SharedPreferences sp = getActivity().getSharedPreferences("Threshold", Activity.MODE_PRIVATE);   //fragment中获取SharedPreferences需要多加一步getActivity()方法

        indUV = view.findViewById(R.id.indUV);
        indClod = view.findViewById(R.id.indClod);
        indDress = view.findViewById(R.id.indDress);
        indMotion = view.findViewById(R.id.indMotion);
        indAir = view.findViewById(R.id.indAir);

        indUV.setImageView(R.drawable.icon101);
        indUV.setTvIndexName("紫外线指数");
        indUV.setTvLevel("中等（100）");
        indUV.setTvAlert("涂擦SPF大于15、PA+防晒护肤品");

        indClod.setImageView(R.drawable.icon102);
        indClod.setTvIndexName("感冒指数");
        indClod.setTvLevel("较易发（5）");
        indClod.setTvAlert("温度低，风较大，较易发生感冒，注意防护");

        indDress.setImageView(R.drawable.icon103);
        indDress.setTvIndexName("穿衣指数");
        indDress.setTvLevel("舒适（21）");
        indDress.setTvAlert("建议穿短袖衬衫、单裤等服装");

        indMotion.setImageView(R.drawable.icon104);
        indMotion.setTvIndexName("运动指数");
        indMotion.setTvLevel("适宜（2000）");
        indMotion.setTvAlert("气候适宜，推荐您进行户外运动");

        indAir.setImageView(R.drawable.icon105);
        indAir.setTvIndexName("空气污染扩散指数");
        indAir.setTvLevel("优（10）");
        indAir.setTvAlert("空气质量非常好，非常适合户外活动，趁机出去多呼吸新鲜空气");

        Timer timer = new Timer();
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                HttpUtil.asyncRequest(new HttpUtil.AsyncCallBack() {
                    @Override
                    public void onFailure(Exception e) {

                    }

                    @Override
                    public void onResponse(String json) {
                        Gson gson = new Gson();
                        ThresholdParams params = gson.fromJson(json, ThresholdParams.class);

                        int Temperature = Integer.parseInt(params.getTemperature());
                        int LightIntensity = Integer.parseInt(params.getLightIntensity());
                        int Co2 = Integer.parseInt(params.getCo2());
                        int Pm25 = Integer.parseInt(params.getPm25());

                        if (sp != null) {
                            indUV.setThresholdAndReality(sp.getInt("Light", 2000), LightIntensity);
                            indClod.setThresholdAndReality(sp.getInt("Temperature", 24), Temperature);
                            indDress.setThresholdAndReality(sp.getInt("Temperature", 24), Temperature);
                            indMotion.setThresholdAndReality(sp.getInt("Co2", 5000), Co2);
                            indAir.setThresholdAndReality(sp.getInt("PM25", 150), Pm25);
                        }

                        if (LightIntensity < 1000) {
                            indUV.setTvLevel("弱（" + LightIntensity + "）");
                            indUV.setTvAlert("辐射较弱，涂擦SPF12~15、PA+护肤品");
                        } else if (LightIntensity <= 3000) {
                            indUV.setTvLevel("中等（" + LightIntensity + "）");
                            indUV.setTvAlert("涂擦SPF大于15、PA+防晒护肤品");
                        } else {
                            indUV.setTvLevel("强（" + LightIntensity + "）");
                            indUV.setTvAlert("尽量减少外出，需要涂抹高倍数防晒霜");
                        }

                        if (Temperature < 8) {
                            indClod.setTvLevel("较易发（" + Temperature + "）");
                            indClod.setTvAlert("温度低，风较大，较易发生感冒，注意防护");
                        } else {
                            indClod.setTvLevel("少发（" + Temperature + "）");
                            indClod.setTvAlert("无明显降温，感冒机率较低");
                        }

                        if (Temperature < 12) {
                            indDress.setTvLevel("冷（" + Temperature + "）");
                            indDress.setTvAlert("建议穿长袖衬衫、单裤等服装");
                        } else if (Temperature <= 21) {
                            indDress.setTvLevel("舒适（" + Temperature + "）");
                            indDress.setTvAlert("建议穿短袖衬衫、单裤等服装");
                        } else {
                            indDress.setTvLevel("热（" + Temperature + "）");
                            indDress.setTvAlert("适合穿T恤、短薄外套等夏季服装");
                        }

                        if (Co2 < 3000) {
                            indMotion.setTvLevel("适宜（" + Co2 + "）");
                            indMotion.setTvAlert("气候适宜，推荐您进行户外运动");
                        } else if (Co2 <= 6000) {
                            indMotion.setTvLevel("中（" + Co2 + "）");
                            indMotion.setTvAlert("易感人群应适当减少室外活动");
                        } else {
                            indMotion.setTvLevel("较不宜（" + Co2 + "）");
                            indMotion.setTvAlert("空气氧气含量低，请在室内进行休闲运动");
                        }

                        if (Pm25 < 30) {
                            indAir.setTvLevel("优（" + Pm25 + "）");
                            indAir.setTvAlert("空气质量非常好，非常适合户外活动，趁机出去多呼吸新鲜空气");
                        } else if (Pm25 <= 100) {
                            indAir.setTvLevel("良（" + Pm25 + "）");
                            indAir.setTvAlert("易感人群应适当减少室外活动");
                        } else {
                            indAir.setTvLevel("污染(" + Pm25 + ")");
                            indAir.setTvAlert("空气质量差，不适合户外活动");
                        }
                    }
                }, "get_all_sense", new String[]{"UserName"}, "user1");
            }
        };
        timer.schedule(timerTask, 0, 3000);
        indUV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(), ThresholdActivity.class);
                startActivity(intent);
            }
        });
        indClod.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(), ThresholdActivity.class);
                startActivity(intent);
            }
        });
        indDress.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(), ThresholdActivity.class);
                startActivity(intent);
            }
        });
        indMotion.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(), ThresholdActivity.class);
                startActivity(intent);
            }
        });
        indAir.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(), ThresholdActivity.class);
                startActivity(intent);
            }
        });

        return view;
    }
}